from .hash_map_base import HashMapBase
from .unsorted_table_map import UnsortedTableMap


class ChainHashMap(HashMapBase):
    """
    基于分离链表实现的HashMap
    """
    def _bucket_getitem(self, j, k):
        """
        从第j个桶里面获取健值为k的值

        """
        bucket = self._table[j]
        if bucket is None:
            raise KeyError("key error: {}".format(repr(k)))
        return bucket[k]

    def _bucket_setitem(self, j, k, v):
        """
        把第j个桶里面获取健值为k的值替换为v
        """
        if self._table[j] is None:
            self._table[j] = UnsortedTableMap()
        oldsize = len(self._table[j])
        self._table[j][k] = v
        if len(self._table[j]) > oldsize:
            self._n += 1

    def _bucket_delitem(self, j, k):
        """
        删除第j个桶里面获取健值为k的值
        """
        bucket = self._table[j]
        if bucket is None:
            raise KeyError("key error: {}".format(repr(k)))
        del bucket[k]

    def __iter__(self):
        for i, bucket in enumerate(self._table):
            if bucket is not None:
                for key in bucket:
                    yield key